/**
 * 认证相关处理
 */
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否有token
    function getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
        return null;
    }

    // 检查token是否有效
    function checkTokenValidity() {
        const token = getCookie('access_token');
        
        if (!token) {
            // 如果没有token，通知页面未认证
            const event = new CustomEvent('auth-check-complete', { 
                detail: { isAuthenticated: false } 
            });
            window.dispatchEvent(event);
            return;
        }
        
        // 如果有token，验证token的有效性
        fetch('/api/validate-token', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
        .then(response => {
            if (!response.ok) {
                // token无效，通知页面未认证
                const event = new CustomEvent('auth-check-complete', { 
                    detail: { isAuthenticated: false } 
                });
                window.dispatchEvent(event);
            } else {
                // token有效，通知页面已认证
                const event = new CustomEvent('auth-check-complete', { 
                    detail: { isAuthenticated: true } 
                });
                window.dispatchEvent(event);
            }
        })
        .catch(() => {
            // 出错时默认认为未认证
            console.log('Token validation failed');
            const event = new CustomEvent('auth-check-complete', { 
                detail: { isAuthenticated: false } 
            });
            window.dispatchEvent(event);
        });
    }

    // 当页面是首页时执行token检查
    if (window.location.pathname === '/' || window.location.pathname === '/index') {
        setTimeout(checkTokenValidity, 500); // 延迟一点执行，确保页面元素已加载
    } else {
        // 非首页，假设已认证（因为其他页面应该已经有了安全控制）
        const event = new CustomEvent('auth-check-complete', { 
            detail: { isAuthenticated: true } 
        });
        window.dispatchEvent(event);
    }
}); 